package com.histone.heartbeat.service;

import com.histone.heartbeat.dao.UrlDao;
import com.histone.heartbeat.pojo.UrlEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

@Service
@Slf4j
public class UrlService {
    @Autowired
    private UrlDao urlDao;

    public UrlEntity saveUrl(UrlEntity urlEntity) {
        log.info("save url {}", urlEntity);
        try {
            URL url = new URL(urlEntity.getUrl());
            InputStream inputStream = url.openStream();
            return urlDao.save(urlEntity);
        } catch (IOException e) {
            log.info("save url error {}, {}", e.getMessage(), urlEntity);
            return null;
        }
    }

    public List<UrlEntity> getUrlsByUserid(@NotNull String userid) {
        return urlDao.findAllByUserid(userid);
    }

    public void delUrl(String id){
        urlDao.deleteById(id);
    }
}
